import React from 'react'
import Icon from '../../../assets/img/sort.png'
import IconAsc from '../../../assets/img/sortAsc.png'
import IconDesc from '../../../assets/img/sortDesc.png'
interface Props {
  label: string,
  sortKey: string,
  data: any,
  onChange: (type: 'desc' | 'asc' | 'none', sortKey: string) => void
}
const PREFIX = 'gzwSort'
class SortTitle extends React.Component<Props, any> {
  constructor(props: Props) {
    super(props)
    this.state = {
      type: 'none',
      data: props.data // 无任何意义，只为存储初始状态
    }
  }
  static getDerivedStateFromProps(nextProps:Props, prevState:any) {
    if (JSON.stringify(nextProps.data) !== JSON.stringify(prevState.data)) {
      return {
        type: 'none',
        data: nextProps.data
      }
    }
    return null
  }
  getClassName(className: string = '') {
    return `${PREFIX}${className}`
  }
  changeType() {
    const { sortKey, onChange } = this.props    
    const { type } = this.state
    let sort = type
    if (type === 'none') {
      sort = 'desc'
    } else if (type === 'desc') {
      sort = 'asc'
    } else {
      sort = 'none'
    }
    this.setState({
      type: sort
    }, () => {
      onChange && onChange(sort, sortKey)
    })
  }
  render() {
    const { label } = this.props
    const { type } = this.state
    return <div className={this.getClassName()} onClick={() => this.changeType()}>
      <div className={this.getClassName('Label')}>{label}</div>
      <div className={this.getClassName('Icon')}>
        {
          type === 'none' && <img src={Icon} alt="" className={this.getClassName('Icon')}/>
        }
        {
          type === 'desc' && <img src={IconDesc} alt="" className={this.getClassName('Icon')}/>
        }
        {
          type === 'asc' && <img src={IconAsc} alt="" className={this.getClassName('Icon')}/>
        }
      </div>
    </div>
  }
}

export default SortTitle
